package com.veetao.api.utils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * List相关的操作
 * 
 * @author Marshal(imdeep@gmail.com) Initial Created at 2013-11-1
 */
public class ListUtils {

    /**
     * 从tSrc中移除tDest中的元素
     * 
     * @param tSrc
     * @param dest
     * @return 被移除的元素
     */
    public static <T> List<T> remove(List<T> tSrc, List<T> tDest) {
        if (tSrc == null) return null;
        List<T> rmd = new ArrayList<T>();
        if (tDest == null || tDest.size() == 0) return rmd;
        return remove(tSrc, new HashSet<T>(tDest));
    }

    /**
     * 从tSrc中移除tDest中的元素
     * 
     * @param tSrc
     * @param dest
     * @return 被移除的元素
     */
    public static <T> List<T> remove(List<T> tSrc, Set<T> tDest) {
        if (tSrc == null) return null;
        List<T> rmd = new ArrayList<T>();
        if (tDest == null || tDest.size() == 0) return rmd;
        for (int i = 0; i < tSrc.size(); i++) {
            T t = tSrc.get(i);
            if (tDest.contains(t)) {
                rmd.add(t);
                tSrc.remove(t);
                i--;
            }
        }
        return rmd;
    }

    /**
     * 取两个集合的交集
     * 
     * @param tSrc
     * @param tDest
     * @return 交集
     */
    public static <T> List<T> retain(List<T> tSrc, List<T> tDest) {
        if (tSrc == null || tDest == null) return null;
        return retain(tSrc, new HashSet<T>(tDest));
    }

    /**
     * 取两个集合的交集
     * 
     * @param tSrc
     * @param tDest
     * @return 交集
     */
    public static <T> List<T> retain(List<T> tSrc, Set<T> tDest) {
        if (tSrc == null || tDest == null) return null;
        List<T> rtd = new ArrayList<T>();
        for (int i = 0; i < tSrc.size(); i++) {
            T t = tSrc.get(i);
            if (tDest.contains(t)) {
                rtd.add(t);
            }
        }
        return rtd;
    }

	/**
	 * @param regIds
	 * @param string
	 * @return
	 * @author guohongtao
	 */
	public static String join(List<? extends Object> list, String delimeter) {
		StringBuilder sb = new StringBuilder();
		for(Object o : list) {
			sb.append(o.toString()).append(delimeter);
		}
		
		int  l = sb.length();
		if(l > 0) {
			int dlen = delimeter.length();
			sb.delete(l - dlen, l);
		}
		
		return sb.toString();
	}

}
